import { ShElement } from './ShElement'
import { ShPopup } from './ShPopup'


export class ShPicker extends ShElement {

    protected $dropdown: ShPopup

    constructor() {
        super()

        this.$shadow.innerHTML = `
            <style>
                :host {
                    border: var(--border-ctrl);
                    width: 100%;
                    background-color: white;
                    outline: none;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                }
                :host(:not([disabled]):hover) {
                    border: solid 1px var(--color-primary);
                }
                :host([disabled]) {
                    color: var(--color-text-gray);
                    background-color: var(--color-ctrl);
                }
                #text {
                    flex-grow: 1;
                    height: 2.5em;
                    line-height: 2.5em;
                    padding: 0 0.5em;
                }
                #icon {
                    padding: 0 0.5em;
                    transition: transform 0.3s;
                    display: flex;
                    align-items: center;
                }
            </style>
            <span id="text"></span>
            <span id="icon">
                <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z" />
                </svg>
            </span>
        `

        if (! this.hasAttribute('disabled'))
            this.setAttribute('tabindex', '0')

        this.on('focus', () => {
            this.addClass('sh-focused')
        })
        this.on('blur', () => {
            this.removeClass('sh-focused')
        })

        this.$dropdown = new ShPopup()
        // 阻止下拉框点击事件的默认行为和传播，防止 host 元素失去焦点
        this.$dropdown.on('pointerdown', (e) => {
            e.preventDefault()
            e.stopPropagation()
        })
        this.$dropdown.on('clickout', () => {
            this.$dropdown.hide()
        })

        const $icon = this.$shadow.getElementById('icon')!
        this.$dropdown.on('shev-popup-show', () => {
            this.focus()
            $icon.style.transform = 'rotate(180deg)'
        })
        this.$dropdown.on('shev-popup-hide', () => {
            $icon.style.transform = ''
        })

        this.on('pointerdown', () => {
            this.$dropdown.show({
                $ref: this,
                position: 'bottom-left',
                anchor: 'top-left',
                offset: { top: 1, left: 0 },
            })
        })
    }

    public get text(): string {
        return this.$shadow.getElementById('text')!.textContent || ''
    }
}
customElements.define('sh-picker', ShPicker)